package view;

import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.*;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import controller.ContactManager;
import model.Contact;
import model.ContactTableModel;
/**
 * This class implements the contactReturner interface, the concerned class
 * can call the retrieveContact data of this class to send data to it
 * @author alexisstefanski
 *
 */
public class MainFrame extends JFrame implements ActionListener, contactReturner{

	/**
	 * Automatically generated by eclipse with implementation of ActionListener
	 */
	private static final long serialVersionUID = 1L;
	
	/* GUI Elements */
	private JLabel focusedContactLabel; 
	private JPanel mainPanel;
	private JButton newButton;
	private JTable contactTable;
	private JButton editButton;
	private JButton deleteButton;
	private Contact selectedContact;
	private JLabel imageLabel;
	
	/* Contact-infos labels */
	private JLabel phonelabel;
	private JLabel addresslabel;
	private JLabel wphonelabel;
	private JLabel waddresslabel;
	private JLabel wmobilelabel;
	private JLabel mobilelabel;
	private JButton weblabel;
	private JLabel skypelabel;
	private JButton emailButton;
	private JLabel grouplabel;
	
	/* Reference to the controller */
	private ContactManager cm;

	public MainFrame(ContactManager cmg) throws HeadlessException {
		super();
		
		this.cm = cmg;
		/** Initialize the layout */
		setTitle("AddressBook");
		setSize(800,600);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		/* Main Panel */
			mainPanel = new JPanel(new BorderLayout());
			this.add(mainPanel);
		
		/* Contact display */
			focusedContactLabel = new JLabel("Nobody selected");
			JPanel contactPanel = new JPanel();
			
			ImageIcon image = new ImageIcon("img/unknown.png");
			// we have to resize the image to 100px width and keep its ratio
			image = new ImageIcon(image.getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT));
			imageLabel = new JLabel(image);
			
			contactPanel.add(imageLabel);
			contactPanel.add(focusedContactLabel);
			
			mainPanel.add(contactPanel, BorderLayout.CENTER);
			newButton = new JButton("New Contact");
			newButton.addActionListener(this);
			mainPanel.add(newButton, BorderLayout.PAGE_START);
			
			editButton = new JButton("Edit");
			editButton.addActionListener(this);
			deleteButton = new JButton("Delete");
			deleteButton.addActionListener(this);
			
			JPanel infosPanel = new JPanel(new GridLayout(11,2));
			mainPanel.add(infosPanel, BorderLayout.LINE_END);
			
			phonelabel= new JLabel();
			addresslabel= new JLabel();
			wphonelabel= new JLabel();
			waddresslabel= new JLabel();
			wmobilelabel= new JLabel();
			mobilelabel= new JLabel();
			weblabel= new JButton();
			skypelabel= new JLabel();
			emailButton= new JButton();
			infosPanel.add(new JLabel("Personnal Phone: "));
			infosPanel.add(phonelabel);
			infosPanel.add(new JLabel("Address: "));
			infosPanel.add(addresslabel);
			infosPanel.add(new JLabel("Work Phone: "));
			infosPanel.add(wphonelabel);
			infosPanel.add(new JLabel("Work Address: "));
			infosPanel.add(waddresslabel);
			infosPanel.add(new JLabel("Work Mobile Phone:"));
			infosPanel.add(wmobilelabel);
			infosPanel.add(new JLabel("Personnal Mobile Phone"));
			infosPanel.add(mobilelabel);
			infosPanel.add(new JLabel("Homepage: "));
			infosPanel.add(weblabel);
			weblabel.addActionListener(this);
			infosPanel.add(new JLabel("Skype username: "));
			infosPanel.add(skypelabel);
			infosPanel.add(new JLabel("Email: "));
			infosPanel.add(emailButton);
			infosPanel.add(new JLabel("Contact group"));
			grouplabel = new JLabel("");
			infosPanel.add(grouplabel);
			emailButton.addActionListener(this);
			infosPanel.add(editButton);
			infosPanel.add(deleteButton);
		
		/* Contact List generation */
			
			ContactTableModel model = new ContactTableModel(cm);
			this.contactTable = new JTable(model);
			contactTable.setAutoCreateRowSorter(true);
			
			/* Add a selection listener to handle selection in the table */
			contactTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
				
				@Override
				public void valueChanged(ListSelectionEvent e) {
						/*Focus the selected contact in the table */
						if(contactTable.getSelectedRow()>=0)
						{
							/* We get the main frame from here and update the selected contact */
							((MainFrame) SwingUtilities.windowForComponent(contactTable)).updateSelectedContact(cm.getContact(contactTable.convertRowIndexToModel(contactTable.getSelectedRow())));
						}
						
				}
			});
			
			/* add a scrollbar to the table */
			JScrollPane listScroller = new JScrollPane(contactTable);
			listScroller.setPreferredSize(new Dimension(250, 80));
			
			mainPanel.add(listScroller,BorderLayout.LINE_START);
			
		
	}

	/**
	 * function fired by the List Selection Listener when selection changes
	 * @param contact
	 */
	protected void updateSelectedContact(Contact contact) {
		
		this.selectedContact=contact;
		
		/*Update Full Name display*/
		focusedContactLabel.setText(selectedContact.getFullName());
	
		/*Handle image display*/
			imageLabel.setIcon(new ImageIcon(selectedContact.getImg().getImage().getScaledInstance(100, (contact.getImg().getImage().getHeight(this))*100/(contact.getImg().getImage().getWidth(this)), Image.SCALE_DEFAULT)));
			//imageLabel.setIcon(new ImageIcon( new ImageIcon("img/unknown.png").getImage().getScaledInstance(100, (new ImageIcon(contact.getImgUrl()).getImage().getHeight(this))*100/(new ImageIcon(contact.getImgUrl()).getImage().getWidth(this)), Image.SCALE_DEFAULT)));

		/*Update all infos in labels*/
		phonelabel.setText(contact.getHomeNumber());
		addresslabel.setText(contact.getHomeAddress());
		wphonelabel.setText(contact.getOfficeNumber());
		waddresslabel.setText(contact.getCompanyAddress());
		wmobilelabel.setText(contact.getWorkMobile());
		mobilelabel.setText(contact.getPersonnalMobile());
		weblabel.setText(contact.getHomepage());
		skypelabel.setText(contact.getSkypeUsername());
		emailButton.setText(contact.getPersonnalEmail());
		grouplabel.setText(contact.getGroup());

	}

	public void addContact(Contact c){
		contactTable.getModel();

	}
	/**
	 * Saves new contact
	 * @param c contact to save
	 */
	public void saveContact(Contact c){
		cm.addContact(c);
		
		updateAndSaveTable();
	}
	/**
	 * Refresh the table and save it in the file
	 */
	public void updateAndSaveTable()
	{
		((ContactTableModel) contactTable.getModel()).fireTableDataChanged();
		cm.saveData();
		cm.saveDataToCsv();
		this.repaint();
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		/*Handle pressed buttons*/
		if (e.getSource()==newButton) {
			ContactFrame cf = new ContactFrame(this);
			cf.setVisible(true);
		}
		if (e.getSource()==editButton) {
			if(selectedContact!=null)
			{
				ContactFrame cf = new ContactFrame(this,selectedContact);
				cf.setVisible(true);
			}
			
		}
		if(e.getSource() == deleteButton) {
			cm.deleteContact(selectedContact);
			((ContactTableModel) contactTable.getModel()).fireTableDataChanged();
			cm.saveData();
			cm.saveDataToCsv();
		}
		if(e.getSource()==weblabel)
		{
			System.out.println("link clicked");
			try {
				openWebpage(new URL(selectedContact.getHomepage()).toURI());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		if(e.getSource()==emailButton)
		{
		    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;

			if ((desktop!=null)&&(desktop.isSupported(Desktop.Action.MAIL))) {
				  URI mailto = null;
				try {
					mailto = new URI("mailto:"+ selectedContact.getPersonnalEmail() +"?subject=Personnal%20Mail");
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				  try {
					desktop.mail(mailto);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				} 
		}
		
		
	}
	public static void openWebpage(URI uri) {
	    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
	    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
	        try {
	        	System.out.println("desktop supported");
	            desktop.browse(uri);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}
	@Override
	public void retrieveContact() {
			updateAndSaveTable();
			updateSelectedContact(selectedContact);
	}

	@Override
	public void retrieveContact(Contact c) {
		saveContact(c);
		
	}

}
